package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryList() {
        // 1. 从redis中查询结果
        String redisKey = "emp:001";
//        String emp = stringRedisTemplate.opsForList().leftPop(redisKey);
        String empJson = stringRedisTemplate.opsForValue().get(redisKey);

        // 2. 如果有数据直接返回：
        if (empJson != null){
            List<ShopType> shop= JSONUtil.toList(empJson,ShopType.class);
            return Result.ok(shop);

        }

        // 3. 如果没有则去查询数据库
        List<ShopType> empList = query().orderByAsc("sort").list();
        if (empList == null){
            return Result.fail("菜单没有数据");
        }
        // 4. 写入到redis中
//        Long aLong=stringRedisTemplate.opsForList().rightPush(redisKey, JSONUtil.toJsonStr(empList));
        stringRedisTemplate.opsForValue().set(redisKey, JSONUtil.toJsonStr(empList));
        //5. 将数据返回出去
        return Result.ok(empList);
    }
}
